import micro86.engine.ParseException;
import micro86.engine.Parser;
import micro86.operation.IOperation;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;

/**
 * (c) Kate Luzhevskaya 2013
 */
public class Loader {
    private static void validateFile(BufferedReader file, Parser parser) throws ParseException{
        int lineNum = 1;

        parser.setIndex(0);
        try {
            String strLine;
            try {
                while ((strLine = file.readLine()) != null)   {
                    parser.parse(strLine);
                    parser.incIndex();
                    lineNum +=1;
                }
            } catch (IOException e) {
                throw new ParseException("File could not be read");
            }
        } catch (ParseException e) {throw new ParseException("\nError in line " + lineNum + " : " + e);}
    }


    private static List<IOperation> getCommandsFromFile (BufferedReader file, Parser parser) throws ParseException{
        int lineNum = 1;
        IOperation operation;
        String strLine;

        parser.setIndex(0);
        try {
            while ((strLine = file.readLine()) != null) {
                parser.finishParse(strLine);
                parser.incIndex();
            }
        } catch (IOException e) {
            throw new ParseException("File could not be read");
        }  catch (ParseException e) {throw new ParseException("\nError in line " + lineNum + " : " + e);}

        return parser.getOperList();

    }

    public static List<IOperation>  processFile(String filePath) throws ParseException {
        BufferedReader bufferedReader = null;
        Parser parser = new Parser();
        try {
            bufferedReader = new BufferedReader(new FileReader(filePath));
            validateFile(bufferedReader, parser);
            bufferedReader = new BufferedReader(new FileReader(filePath));
            List<IOperation> commandList = getCommandsFromFile(bufferedReader, parser);
            return commandList;
        }
        catch (FileNotFoundException e) {
            throw new ParseException("File " + filePath + " not found.");
        }
        catch (ParseException e) {
            throw new ParseException("Error with file " + filePath + " : " + e);
        }
        finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException e) {
                // ignore
            }
        }
    }

}
